package cc.linker.steplink.crm.service.impl;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.dao.TemplateMessageDao;
import cc.linker.steplink.crm.merchant.dao.NewMallDao;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.ITemplateMessageService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
@Service
public class TemplateMessageImpl implements ITemplateMessageService {

    @Autowired
    private NewMallDao newMallDao;

    @Autowired
    private TemplateMessageDao tempMsgDao;

    @Autowired
    private HttpService httpService;

    @Value("${system.scrm.wxpushurl}")
    private String url;

    @Override
    public List<Map<String, Object>> list(String orgId) {
        return tempMsgDao.listTempMsg(orgId);
    }

    @Override
    public Boolean edit(Map record) throws Exception {
        if(1 == tempMsgDao.edit(record)){
            return true;
        }
        return false;
    }

    @Override
    public HashMap<String, Object> getInfo(String templateMessageId) {
        return tempMsgDao.getInfo(templateMessageId);
    }

    @Override
    public void add(Map record){
        if(tempMsgDao.getMsgCount(record)==0){
            tempMsgDao.add(record);
        }
    }

    /**
     *
     * @param data
     * orgId-机构id,goodsName-商品名称,orderSn-订单号,orderAmount-订单金额(非支付金额),orderTime-支付时间,url-订单列表页面,openid-购买人的openid
     * @throws IOException
     * @throws URISyntaxException
     */
    @Override
    public void sendPayMsg(Map<String,String> data) throws IOException, URISyntaxException {
        String orgId = data.get("orgId");
        if(StringUtils.isEmpty(orgId)){
            throw GlobalException.build("参数错误");
        }
        Map<String, Object> template = tempMsgDao.getTemplate(orgId, "3");
        if(null == template){
            return;
        }
        if("0".equals(template.get("status").toString()) || StringUtils.isEmpty(template.get("templateId"))){
            return;
        }
        Map<String, Object> pushdata = new HashMap<>();
        Map<String, Object> jsondata = new TreeMap<>();
        Map<String, String> first = new TreeMap<>();
        first.put("value","下单成功啦,您可在个人中心的订单页面查看。");
        jsondata.put("first",first);
        Map<String, String> keyword1 = new TreeMap<>();
        keyword1.put("value",data.get("goodsName"));
        jsondata.put("keyword1",keyword1);
        Map<String, String> keyword2 = new TreeMap<>();
        keyword2.put("value",data.get("orderSn"));
        jsondata.put("keyword2",keyword2);
        Map<String, String> keyword3 = new TreeMap<>();
        keyword3.put("value",data.get("orderAmount"));
        jsondata.put("keyword3",keyword3);
        Map<String, String> keyword4= new TreeMap<>();
        keyword4.put("value",data.get("orderTime"));
        jsondata.put("keyword4",keyword4);
        Map<String, String> remark= new TreeMap<>();
        remark.put("value","感谢您的光临!");
        jsondata.put("remark",remark);

        pushdata.put("action", "sendWxMessage");
        pushdata.put("token",newMallDao.getTokenByOrgId(orgId));
        pushdata.put("openid",data.get("openid"));
        pushdata.put("url",data.get("url"));
        pushdata.put("template_id",template.get("templateId").toString());
        pushdata.put("data", jsondata);

        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(pushdata);
        httpService.doPost(url,jsonObject.toJSONString(),postParam);
    }

    /**
     *
     * @param data
     * orgId-机构id,orderSn-订单号,sendTime-订单发货的时间,expressCompany-物流公司：发货时填写，没有则展示“不需要物流”,
     * expressSn-快递单号：发货时填写，没有则展示“不需要物流”,receiveInfo-收件信息：收货人+手机号+收货地址（王先生 135xxxxxxxx 广东省深圳市龙华区建设东路）
     * url-订单列表页面,openid-购买人的openid
     * @throws IOException
     * @throws URISyntaxException
     */
    @Override
    public void sendDeliveryMsg(Map<String,String> data) throws IOException, URISyntaxException {
        String orgId = data.get("orgId");
        if(StringUtils.isEmpty(orgId)){
            throw GlobalException.build("参数错误");
        }
        Map<String, Object> template = tempMsgDao.getTemplate(orgId, "4");
        if(null == template){
            return;
        }
        if("0".equals(template.get("status").toString()) || StringUtils.isEmpty(template.get("templateId"))){
            return;
        }
        Map<String, Object> pushdata = new HashMap<>();
        Map<String, Object> jsondata = new TreeMap<>();
        Map<String, String> first = new HashMap<>();
        first.put("value","您购买的订单已经发货啦，正快马加鞭向您飞奔而去。");
        jsondata.put("first",first);
        Map<String, String> keyword1 = new HashMap<>();
        keyword1.put("value",data.get("orderSn"));
        jsondata.put("keyword1",keyword1);
        Map<String, String> keyword2 = new HashMap<>();
        keyword2.put("value",data.get("sendTime"));
        jsondata.put("keyword2",keyword2);
        Map<String, String> keyword3 = new HashMap<>();
        keyword3.put("value",data.get("expressCompany"));
        jsondata.put("keyword3",keyword3);
        Map<String, String> keyword4 = new HashMap<>();
        keyword4.put("value",data.get("expressSn"));
        jsondata.put("keyword4",keyword4);
        Map<String, String> keyword5 = new HashMap<>();
        keyword5.put("value",data.get("receiveInfo"));
        jsondata.put("keyword5",keyword5);
        Map<String, String> remark = new HashMap<>();
        remark.put("value","请保持收件手机畅通！");
        jsondata.put("remark",remark);
        pushdata.put("action", "sendWxMessage");
        pushdata.put("token",newMallDao.getTokenByOrgId(orgId));
        pushdata.put("openid",data.get("openid"));
        pushdata.put("url",data.get("url"));
        pushdata.put("template_id",template.get("templateId").toString());
        pushdata.put("data",jsondata);
        LOGGER.info("sendDeliveryMsg---"+ com.alibaba.fastjson.JSON.toJSONString(pushdata));
        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(pushdata);
        httpService.doPost(url,jsonObject.toJSONString(),postParam);
    }
}
